import os
import time
from django.shortcuts import render
from django.http import HttpResponse

from FileUpload.paddleutils import ocrfile,drawimg

from PaddleWebServer import settings

#from paddle_ocr import paddle_ocr

# Create your views here.
def upload(request):
    context = {}
    return render(request, 'uploadfile.html',context)

#上传文件方法
def uploadFile(request):
    # 请求方法为POST时,进行处理;
    if request.method == "POST":
        # 获取上传的文件,如果没有文件,则默认为None;
        File = request.FILES.get("file_img", None)
        if File is None:
            return HttpResponse("no files for upload!")
        else:
            filename = File.name       #视频文件的本来名称
            filedate = int(time.time()) #获取时间戳并将其转为整数
            fileName = str(filedate)+filename  #将时间戳和文件的本来名称进行拼接
            fileName = os.path.join(settings.MEDIA_ROOT,fileName)
            out_path = 'result.jpg'
            out_path_rel = os.path.join(settings.MEDIA_ROOT,out_path)
            f = open(fileName,'wb') #新建文件
            for chunk in File.chunks():  #chunks()方法可以按块读取容量较大的文件
                f.write(chunk)
            f.close()
            result = ocrfile(fileName)
            drawimg(File,result,out_path_rel)
            
            res=""
            for line in result:
                print(line)
                res+=str(line)+"<br/>"
            
            context = {}
            context['result'] = result
            context['image_path'] = out_path
            #return HttpResponse(result)
            return render(request, 'finish.html',context)
    else:
        return render(request, 'index.html')
